﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace AutoInstallUtil
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ServerAction();
            }
            catch (Exception ex)
            {
                Console.WriteLine("发生错误：{0}", ex.Message);
            }

            Console.ReadKey();
        }

        /// <summary>
        /// 操作
        /// </summary>
        private static void ServerAction()
        {
            Console.WriteLine("请输入：1安装  2卸载");
            var condition = Console.ReadLine();
            var currentPath = Environment.CurrentDirectory;
            var currentFileNameVshost = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName).ToLower();
            var currentFileName = currentFileNameVshost.Replace(".vshost.exe", ".exe");
            var files =
                Directory.GetFiles(currentPath)
                    .Select(o => Path.GetFileName(o).ToLower())
                    .ToList()
                    .Where(
                        o =>
                            o != currentFileNameVshost
                            && o != currentFileName
                            && o.ToLower().EndsWith(".exe")
                            && o != "installutil.exe"
                            && !o.ToLower().EndsWith(".vshost.exe"))
                    .ToList();
            if (files.Count == 0)
            {
                Console.WriteLine("未找到可执行文件，请确认当前目录有需要安装的服务程序");
            }
            else
            {
                Console.WriteLine("找到目录有如下可执行文件，请选择需要安装或卸载的文件序号：");
            }
            int i = 0;
            foreach (var file in files)
            {
                Console.WriteLine("序号：{0}  文件名：{1}", i, file);
                i++;
            }
            var serviceFileIndex = Console.ReadLine();
            var servicePathName = currentPath + "\\" + files[Convert.ToInt32(serviceFileIndex)];
            if (condition == "1")
            {
                SystemServices.InstallService(null, servicePathName);
            }
            else
            {
                SystemServices.UnInstallService(servicePathName);
            }
            Console.WriteLine("**********本次操作完毕**********");
            ServerAction();
        }
    }
}
